package com.frontop.terminal.downloader;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.frontop.terminal.entity.FilePart;
import com.frontop.terminal.entity.TerminalConfig;
import com.frontop.terminal.enums.HeaderEnum;
import com.frontop.terminal.util.ReadDataUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * 多线程下载
 *
 * @author Guodong
 */
@Slf4j
public class Downloader implements Runnable {
    private final Integer id;
    private final Long from;
    private final Long to;
    private final File target;
    private final String uri;

    public Downloader(Integer id, Long from, Long to, File target, String uri) {
        this.id = id;
        this.from = from;
        this.to = to;
        this.target = target;
        this.uri = uri;
    }

    @Override
    public void run() {
        //download and save data
        try {
            TerminalConfig terminalConfig = ReadDataUtil.getTerminalConfig();
            HttpURLConnection connection = (HttpURLConnection) new URL(uri).openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Range", "bytes=" + from + "-" + to);
            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            connection.setRequestProperty(HeaderEnum.TERMINAL_TOKEN.getKey(), terminalConfig.getAuthorizationCode());
            //读取数据超时2分钟
            connection.setReadTimeout(1000 * 60 * 2);
            //连接超时10秒
            connection.setConnectTimeout(1000 * 10);
            connection.connect();
            long s = connection.getContentLengthLong();
            InputStream inputStream = connection.getInputStream();
            log.info("分片获取文件大小" + inputStream.available());
            RandomAccessFile randomAccessFile = new RandomAccessFile(target, "rw");
            randomAccessFile.seek(from);
            byte[] buffer = new byte[1024];
            int readCount = inputStream.read(buffer, 0, buffer.length);
            while (readCount > 0) {
                s -= readCount;
                System.out.println("分片" + id + "剩余:" + s);
                randomAccessFile.write(buffer, 0, readCount);
                readCount = inputStream.read(buffer, 0, buffer.length);
            }
            inputStream.close();
            randomAccessFile.close();

            //更新线程分片任务状态
            updatePartTas();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void updatePartTas() {
        String json = ReadDataUtil.read(target.getPath() + ".tmp");
        List<FilePart> fileParts = JSON.parseArray(json, FilePart.class, ParserConfig.global);
        assert fileParts != null;
        for (FilePart fp : fileParts) {
            if (fp.getId().equals(this.id)) {
                fp.setStatus(true);
            }
        }
        //更新
        MultipleThreadDownloadTask.savePartTas(fileParts);
    }

}
